package main

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type User struct {
	gorm.Model  `json:"username" gorm:"column:username"`
	Username    string
	CreditCards []CreditCard
}

type CreditCard struct {
	gorm.Model
	Number string
	UserId uint
}

func main() {
	//0.连接数据库
	dsn := "root:chencheng233@tcp(127.0.0.1:3306)/test_db?charset=utf8mb4&parseTime=True&loc=Local"
	db, _ := gorm.Open(mysql.Open(dsn), &gorm.Config{})

	//创建表结构
	//db.AutoMigrate(User{}, CreditCard{})

	user := User{
		Username: "zhangsan",
		CreditCards: []CreditCard{
			{Number: "0001"},
			{Number: "0002"},
		},
	}
	db.Create(&user)

	//2. 为已存在的用户添加信用卡,找到用户
	u := User{Username: "zhangsan"}
	//要对数据库进行操作就得先First
	db.First(&u)
	db.Model(&u).Association("CreditCards").Append([]CreditCard{
		{Number: "0003"},
	})
}
